package com.baor.aspectj;


import com.baor.dao.SyslogDao;
import com.baor.domain.AdminVo;
import com.baor.domain.SyslogVo;
import com.baor.seacurity.TokenService;
import com.baor.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import static com.baor.utils.DateUtil.now;

@Aspect
@Component
public class SyslogAspect {

    private static final ThreadLocal<Long> TIME_THREADLOCAL = new NamedThreadLocal<>("Cost Time");

    @Autowired
    private SyslogDao syslogDao;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private TokenService tokenService;

    @Pointcut("execution(* com.baor.service..*.*(..))")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        //获取当前请求路径
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String requestPath = attributes.getRequest().getRequestURI();

        //方法主体执行之前
        TIME_THREADLOCAL.set(System.currentTimeMillis());

        Object proceed = pjp.proceed();

        //方法主体执行之后
        try {
            SyslogVo vo = new SyslogVo();
            String authorization = attributes.getRequest().getHeader("authorization");
            Claims claims = tokenService.getBody(authorization);
            System.out.println(authorization);
            String userAccount = claims.getSubject();
            System.out.println(userAccount);
            System.out.println(redisUtil.getValue("userAccount:"+userAccount));
            AdminVo user = (AdminVo) redisUtil.getValue("userAccount:"+userAccount);
            vo.setCreateTime(now());
            vo.setSyslogOperate(requestPath);
            vo.setSiteId(String.valueOf(1));
            vo.setSyslogHttp(String.valueOf(attributes.getRequest().getMethod()));
            vo.setAdminId(Math.toIntExact(user.getAdminId()));
            vo.setSyslogIp(user.getAdminIp());
            syslogDao.insert(vo);
        } catch (Exception ex) {
            System.out.println("异常信息:{}" + ex.getMessage());
            ex.printStackTrace();
        } finally {
            TIME_THREADLOCAL.remove();
        }
        return proceed;

    }
}
